Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
json-2-csv
Advanced tools
A JSON to CSV and CSV to JSON converter that natively supports sub-documents and auto-generates the CSV heading.
The json-2-csv npm package is a utility for converting JSON data to CSV format and vice versa. It is useful for data transformation tasks, especially when dealing with data interchange between systems that use different formats.
Convert JSON to CSV
This feature allows you to convert an array of JSON objects into a CSV string. The code sample demonstrates how to use the json2csv function to transform JSON data into CSV format.
const json2csv = require('json-2-csv');
const json = [
{ name: 'John', age: 30, city: 'New York' },
{ name: 'Anna', age: 22, city: 'London' },
{ name: 'Mike', age: 32, city: 'Chicago' }
];
json2csv.json2csv(json, (err, csv) => {
if (err) {
throw err;
}
console.log(csv);
});
Convert CSV to JSON
This feature allows you to convert a CSV string into an array of JSON objects. The code sample demonstrates how to use the csv2json function to transform CSV data into JSON format.
const json2csv = require('json-2-csv');
const csv = 'name,age,city\nJohn,30,New York\nAnna,22,London\nMike,32,Chicago';
json2csv.csv2json(csv, (err, json) => {
if (err) {
throw err;
}
console.log(json);
});
Custom Delimiters
This feature allows you to specify custom delimiters for fields and arrays when converting JSON to CSV. The code sample demonstrates how to use the json2csv function with custom delimiter options.
const json2csv = require('json-2-csv');
const json = [
{ name: 'John', age: 30, city: 'New York' },
{ name: 'Anna', age: 22, city: 'London' },
{ name: 'Mike', age: 32, city: 'Chicago' }
];
const options = {
delimiter: {
field: ';',
array: '|'
}
};
json2csv.json2csv(json, (err, csv) => {
if (err) {
throw err;
}
console.log(csv);
}, options);
The csv-parser package is a streaming CSV parser that converts CSV data into JSON objects. It is highly efficient for processing large CSV files. Unlike json-2-csv, which provides both JSON to CSV and CSV to JSON conversion, csv-parser focuses solely on parsing CSV to JSON.
The papaparse package is a powerful CSV parser that can handle large files and supports web workers for asynchronous parsing. It offers both CSV to JSON and JSON to CSV conversion, similar to json-2-csv, but with additional features like streaming and chunking for large datasets.
The fast-csv package is a comprehensive library for parsing and formatting CSV data. It supports both reading from and writing to CSV files, similar to json-2-csv. However, fast-csv is designed for high performance and can handle large datasets efficiently.
Convert JSON to CSV or CSV to JSON
This node module will convert an array of JSON documents to a CSV string. Column headings will be automatically generated based on the keys of the JSON documents. Nested documents will have a '.' appended between the keys.
It is also capable of converting CSV of the same form back into the original array of JSON documents. The columns headings will be used as the JSON document keys. All lines must have the same exact number of CSV values.
$ npm install json-2-csv
CLI:
$ npm install @mrodrig/json-2-csv-cli
Upgrading to v3 from v2? Check out the upgrade guide.
let converter = require('json-2-csv');
or
import { json2csv } from 'json-2-csv';
Looking for examples? Check out the Wiki: json-2-csv Wiki
converter.json2csv(array, callback, options)
array
- An array of JSON documents to be converted to CSV.callback
- A function of the form function (err, csv)
;
options
- (Optional) A JSON document specifying any of the following key value pairs:
checkSchemaDifferences
- Boolean - Should all documents have the same schema?
false
true
.delimiter
- Document - Specifies the different types of delimiters
field
- String - Field Delimiter.
,
wrap
- String - Wrap values in the delimiter of choice (e.g. wrap values in quotes).
"
eol
- String - End of Line Delimiter.
\n
emptyFieldValue
- Any - Value that, if specified, will be substituted in for field values that are undefined
, null
, or an empty string.
excelBOM
- Boolean - Should a unicode character be prepended to allow Excel to open a UTF-8 encoded file with non-ASCII characters present.excludeKeys
- Array - Specify the keys that should be excluded from the output.
[]
unwindArrays
, arrays present at excluded key paths will not be unwound.expandArrayObjects
- Boolean - Should objects in array values be deep-converted to CSV?
false
[
{
"specifications": [
{ "features": [...] },
{ "mileage": "5000" }
]
}
]
true
uses the following keys:
['specifications.features', 'specifications.mileage']
false
uses the following keys:
['specifications']
keys
- Array - Specify the keys that should be converted.
field
property specifying the path. When specifying keys as an Object, you can also optionally specify a title
which will be used for that column in the header. The list specified can contain a combination of Objects and Strings.
[ 'key1', 'key2', ... ]
[ { field: 'key1', title: 'Key 1' }, { field: 'key2' }, 'key3', ... ]
parseValue
- Function - Specify how values should be converted into CSV format. This function is provided a single field value at a time and must return a String
. The built-in parsing method is provided as the second argument for cases where default parsing is preferred.
useDateIso8601Format
and useLocaleFormat
.prependHeader
- Boolean - Should the auto-generated header be prepended as the first line in the CSV?
true
sortHeader
- Boolean or Function - Should the header keys be sorted in alphabetical order? or pass a function to use a custom sorting function
false
trimFieldValues
- Boolean - Should the field values be trimmed?
false
trimHeaderFields
- Boolean - Should the header fields be trimmed?
false
unwindArrays
- Boolean - Should array values be "unwound" such that there is one line per value in the array?
false
[
{
"_id": {"$oid": "5cf7ca3616c91100018844af"},
"data": {"category": "Computers", "options": [{"name": "MacBook Pro 15"}, {"name": "MacBook Air 13"}]}
},
{
"_id": {"$oid": "5cf7ca3616c91100018844bf"},
"data": {"category": "Cars", "options": [{"name": "Supercharger"}, {"name": "Turbocharger"}]}
}
]
true
will unwind the JSON to four objects, and therefore four lines of CSV values:_id.$oid,data.category,data.options.name
5cf7ca3616c91100018844af,Computers,MacBook Pro 15
5cf7ca3616c91100018844af,Computers,MacBook Air 13
5cf7ca3616c91100018844bf,Cars,Supercharger
5cf7ca3616c91100018844bf,Cars,Turbocharger
false
will leave the values unwound and will convert the array as-is (when this option is used without expandArrayObjects):_id.$oid,data.category,data.options
5cf7ca3616c91100018844af,Computers,"[{""name"":""MacBook Pro 15""},{""name"":""MacBook Air 13""}]"
5cf7ca3616c91100018844bf,Cars,"[{""name"":""Supercharger""},{""name"":""Turbocharger""}]"
useDateIso8601Format
- Boolean - Should date values be converted to an ISO8601 date string?
false
toISOString()
rather than toString()
or toLocaleString()
depending on the other options provided.useLocaleFormat
- Boolean - Should values be converted to a locale specific string?
false
toLocaleString()
rather than toString()
wrapBooleans
- Boolean - Should boolean values be wrapped in wrap delimiters to prevent Excel from converting them to Excel's TRUE/FALSE Boolean values.
false
preventCsvInjection
- Boolean - Should CSV injection be prevented by left trimming these characters: Equals (=), Plus (+), Minus (-), At (@), Tab (0x09), Carriage return (0x0D).
false
For examples, please refer to the json2csv API Documentation (Link)
converter.json2csvAsync(array, options)
Available in version 2.2.0
, this functionality makes use of promises from the bluebird
module.
converter.csv2json(csv, callback, options)
csv
- A string of CSVcallback
- A function of the form function (err, array)
; This function will receive any errors and/or the array of JSON documents generated.options
- (Optional) A JSON document specifying any of the following key value pairs:
delimiter
- Document - Specifies the different types of delimiters
field
- String - Field Delimiter.
,
wrap
- String - The character that field values are wrapped in.
"
eol
- String - End of Line Delimiter.
\n
excelBOM
- Boolean - Does the CSV contain a unicode character prepended in order to allow Excel to open a UTF-8 encoded file with non-ASCII characters present?
false
headerFields
- Array - Specify the field names (as strings) in place of a header line in the CSV itself.
{info : {name: 'Mike'}}
), then use .
characters in the string to denote a nested field, like ['info.name']keys
- Array - Specify the keys (as strings) that should be converted.
null
{info : {name: 'Mike'}}
), then set this to ['info.name']
null
or don't specify the option to utilize the default.parseValue
- Function - Specify how String
representations of field values should be parsed when converting back to JSON. This function is provided a single String
and can return any value.
JSON.parse
- An attempt is made to convert the String back to its original value using JSON.parse
.trimHeaderFields
- Boolean - Should the header fields be trimmed?
false
trimFieldValues
- Boolean - Should the field values be trimmed?
false
For examples, please refer to the csv2json API Documentation (Link)
csv2jsonAsync(csv, options)
Available in version 2.2.0
, this functionality makes use of promises from the bluebird
module.
Note: As of 3.5.8
, the command line interface functionality has been pulled out to a separate package. Please be sure to
install the @mrodrig/json-2-csv-cli
NPM package if you wish to use the CLI functionality shown below:
$ npm install @mrodrig/json-2-csv-cli
Usage: json2csv <jsonFile> [options]
Options:
-V, --version output the version number
-o, --output [output] Path of output file. If not provided, then stdout will be used
-f, --field <delimiter> Optional field delimiter
-w, --wrap <delimiter> Optional wrap delimiter
-e, --eol <delimiter> Optional end of line delimiter
-b, --excel-bom Excel Byte Order Mark character prepended to CSV
-W, --without-header Withhold the prepended header
-s, --sort-header Sort the header fields
-H, --trim-header Trim header fields
-F, --trim-fields Trim field values
-S, --check-schema Check for schema differences
-E, --empty-field-value <value> Empty field value
-A, --expand-array-objects Expand array objects
-k, --keys [keys] Keys of documents to convert to CSV
-h, --help output usage information
Usage: csv2json <csvFile> [options]
Options:
-V, --version output the version number
-c, --csv <csv> Path of json file to be converted
-o, --output [output] Path of output file. If not provided, then stdout will be used
-f, --field <delimiter> Optional field delimiter
-w, --wrap <delimiter> Optional wrap delimiter
-e, --eol <delimiter> Optional end of line delimiter
-b, --excel-bom Excel Byte Order Mark character prepended to CSV
-H, --trim-header Trim header fields
-F, --trim-fields Trim field values
-k, --keys [keys] Keys of documents to convert to CSV
-h, --help output usage information
$ npm test
To see test coverage, please run:
$ npm run coverage
Current Coverage is:
Statements : 100% ( 286/286 )
Branches : 100% ( 166/166 )
Functions : 100% ( 73/73 )
Lines : 100% ( 280/280 )
Please find the updated list (relocated to the Wiki) here: Frequently Asked Questions (Link)
csv2json test.csv -o output.json
json2csv test.json -o output.csv -W -k arrayOfStrings -o output.csv
FAQs
A JSON to CSV and CSV to JSON converter that natively supports sub-documents and auto-generates the CSV heading.
The npm package json-2-csv receives a total of 405,941 weekly downloads. As such, json-2-csv popularity was classified as popular.
We found that json-2-csv demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.